const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const { app: electronApp } = require('electron')

let bubbleWindow = null
let noteWindows = []
let settingsWindow = null
let isNotesVisible = true

// 设置自启动
function setAutoLaunch(enable) {
    console.log('设置开机自启动:', enable)
    if (process.platform === 'darwin') {
        app.setLoginItemSettings({
            openAtLogin: enable,
            path: process.execPath
        })
    } else if (process.platform === 'win32') {
        app.setLoginItemSettings({
            openAtLogin: enable,
            path: process.execPath,
            args: []
        })
    }
    // 验证设置是否成功
    const status = getAutoLaunchStatus()
    console.log('当前自启动状态:', status)
}

// 获取自启动状态
function getAutoLaunchStatus() {
    const status = app.getLoginItemSettings().openAtLogin
    console.log('获取自启动状态:', status)
    return status
}

function createBubbleWindow() {
    // 获取屏幕尺寸
    const { screen } = require('electron')
    const primaryDisplay = screen.getPrimaryDisplay()
    const { width, height } = primaryDisplay.workAreaSize

    bubbleWindow = new BrowserWindow({
        width: 200,
        height: 200,
        x: Math.floor(width / 2 - 100),  // 居中显示
        y: height / 2,  // 底部显示，留出一些边距
        frame: false,
        transparent: true,
        alwaysOnTop: true,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        },
        acceptFirstMouse: true,
        movable: true,
        enableLargerThanScreen: true,
        resizable: false,
        skipTaskbar: true,
        hasShadow: false
    })

    bubbleWindow.loadFile(path.join(__dirname, '../renderer/bubble.html'))
    
    // 防止气泡被拖到屏幕外
    bubbleWindow.on('move', () => {
        const [x, y] = bubbleWindow.getPosition()
        const bounds = screen.getPrimaryDisplay().workAreaSize

        if (x < 0) bubbleWindow.setPosition(0, y)
        if (y < 0) bubbleWindow.setPosition(x, 0)
        if (x + 200 > bounds.width) bubbleWindow.setPosition(bounds.width - 200, y)
        if (y + 200 > bounds.height) bubbleWindow.setPosition(x, bounds.height - 200)
    })
}

function createNoteWindow() {
    const noteWindow = new BrowserWindow({
        width: 300,
        height: 300,
        frame: false,
        transparent: true,
        alwaysOnTop: true,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
        },
        movable: true,
        acceptFirstMouse: true,
        enableLargerThanScreen: true,
        skipTaskbar: true,
        hasShadow: false
    })

    noteWindow.loadFile(path.join(__dirname, '../renderer/index.html'))
    noteWindows.push(noteWindow)

    noteWindow.on('closed', () => {
        noteWindows = noteWindows.filter(win => win !== noteWindow)
    })
}

// 创建设置窗口
function createSettingsWindow() {
    if (settingsWindow) {
        settingsWindow.focus()
        return
    }

    // 获取气泡窗口的位置和大小
    const bubblePosition = bubbleWindow.getPosition()
    const bubbleSize = bubbleWindow.getSize()
    
    // 计算设置窗口的位置（在气泡右侧）
    const settingsX = bubblePosition[0] + bubbleSize[0] + 10
    const settingsY = bubblePosition[1]

    settingsWindow = new BrowserWindow({
        width: 340,
        height: 500,
        x: settingsX,
        y: settingsY,
        frame: false,
        transparent: true,
        alwaysOnTop: true,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true
        },
        resizable: false,
        movable: true,
        skipTaskbar: true,
        acceptFirstMouse: true,
        hasShadow: false
    })

    settingsWindow.loadFile(path.join(__dirname, '../renderer/settings.html'))

    // 确保设置窗口不会超出屏幕边界
    const { screen } = require('electron')
    const primaryDisplay = screen.getPrimaryDisplay()
    const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize

    const [x, y] = settingsWindow.getPosition()
    const [width, height] = settingsWindow.getSize()

    if (x + width > screenWidth) {
        // 如果超出右边界，就放在气泡左侧
        settingsWindow.setPosition(bubblePosition[0] - width - 10, y)
    }
    if (y + height > screenHeight) {
        // 如果超出下边界，就向上移动
        settingsWindow.setPosition(settingsWindow.getPosition()[0], screenHeight - height)
    }

    settingsWindow.on('closed', () => {
        settingsWindow = null
    })
}

app.whenReady().then(() => {
    createBubbleWindow()
})

// 在应用退出时注销快捷键
app.on('will-quit', () => {
    app.quit()
})

// 监听气泡点击事件
ipcMain.on('toggle-bubble-menu', () => {
    bubbleWindow.webContents.send('show-bubble-menu')
})

// 监听添加便签事件
ipcMain.on('add-note', () => {
    createNoteWindow()
})

// 监听显示/隐藏便签事件
ipcMain.on('toggle-notes-visibility', (event) => {
    // 过滤掉已经销毁的窗口
    noteWindows = noteWindows.filter(win => !win.isDestroyed())
    
    // 检查是否有便签
    if (noteWindows.length === 0) {
        // 如果没有便签，发送提示消息
        event.reply('no-notes-to-toggle')
        return
    }

    isNotesVisible = !isNotesVisible
    noteWindows.forEach(win => {
        try {
            if (isNotesVisible) {
                if (!win.isDestroyed()) {
                    win.show()
                }
            } else {
                if (!win.isDestroyed()) {
                    win.hide()
                }
            }
        } catch (error) {
            console.error('切换便签可见性时出错:', error)
        }
    })
})

// 处理窗口大小调整
ipcMain.on('resize-note', (event, settings) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
        win.setSize(settings.width, settings.height)
    }
})

// 更新所有便签的设置
ipcMain.on('update-notes-settings', (event, settings) => {
    try {
        // 过滤掉已经销毁的窗口并更新所有打开的便签窗口
        noteWindows = noteWindows.filter(win => !win.isDestroyed())
        noteWindows.forEach(win => {
            try {
                if (!win.isDestroyed()) {
                    win.setSize(settings.width, settings.height)
                    win.webContents.send('update-settings', settings)
                }
            } catch (error) {
                console.error('更新便签设置时出错:', error)
            }
        })
    } catch (error) {
        console.error('保存设置时出错:', error)
    }
})

// 修改关闭便签的监听
ipcMain.on('close-note', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
        // 先从数组中移除
        noteWindows = noteWindows.filter(w => w !== win && !w.isDestroyed())
        // 再销毁窗口
        if (!win.isDestroyed()) {
            win.destroy()
        }
    }
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

// 添加拖动相关的 IPC 监听
ipcMain.on('start-drag-mode', () => {
    if (bubbleWindow && !bubbleWindow.isDestroyed()) {
        bubbleWindow.setIgnoreMouseEvents(false)
    }
})

// 更新气泡位置的监听
ipcMain.on('update-bubble-position', (event, { x, y }) => {
    if (bubbleWindow && !bubbleWindow.isDestroyed()) {
        const newX = Math.round(x - 100)
        const newY = Math.round(y - 160)
        
        const { screen } = require('electron')
        const bounds = screen.getPrimaryDisplay().workAreaSize

        const finalX = Math.max(0, Math.min(newX, bounds.width - 200))
        const finalY = Math.max(0, Math.min(newY, bounds.height - 200))

        bubbleWindow.setPosition(finalX, finalY)
    }
})

ipcMain.on('end-drag-mode', () => {
    if (bubbleWindow && !bubbleWindow.isDestroyed()) {
        bubbleWindow.setIgnoreMouseEvents(false)
    }
})

// 监听打开设置窗口事件
ipcMain.on('open-settings', () => {
    createSettingsWindow()
})

// 监听自启动设置
ipcMain.on('set-auto-launch', (event, enable) => {
    console.log('收到自启动设置请求:', enable)
    setAutoLaunch(enable)
})

// 获取自启动状态
ipcMain.on('get-auto-launch', (event) => {
    const enabled = getAutoLaunchStatus()
    console.log('发送自启动状态:', enabled)
    event.reply('auto-launch-status', enabled)
})

// 监听退出程序事件
ipcMain.on('quit-app', () => {
    console.log('主进程收到退出信号')
    try {
        // 关闭所有窗口
        BrowserWindow.getAllWindows().forEach(window => {
            if (!window.isDestroyed()) {
                window.destroy()
            }
        })
        // 退出程序
        app.quit()
    } catch (error) {
        console.error('退出过程中出错:', error)
        app.exit(0) // 强制退出
    }
}) 